<template>
  <el-row :gutter="24">
    <el-col :span="16">
      <el-form
        ref="ruleForm"
        :inline="true"
        :rules="rules"
        :model="system_right.groups[dataId]"
      >
        <el-form-item label="权限组名称" prop="groupsName">
          <el-input
            maxlength="10"
            v-model="system_right.groups[dataId].groupsName"
            placeholder="权限组名称"
          />
        </el-form-item>
        <el-form-item label="排序值" prop="groupsSort">
          <el-input
            v-model.number="system_right.groups[dataId].groupsSort"
            maxlength="3"
            placeholder="排序值越大越靠前"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addTab(editableTabsValue)"
            >保存</el-button
          >
          <el-button type="primary" @click="delTab(editableTabsValue)"
            >删除</el-button
          >
        </el-form-item>
      </el-form>
      <el-col :span="24">
        <el-tabs class="table-form-detail" type="border-card">
          <el-tab-pane v-for="item in system_right.menuList">
            <span slot="label">{{ item.menuName }}</span>
            <el-checkbox-group v-model="checkList">
              <div v-for="e in item.children">
                <p v-if="!e.hidden" class="tablemenu-title">
                  <el-checkbox
                    :label="e.id"
                    @change="(i) => handleCheckAllChange(i, e.id)"
                    >{{ e.menuName }}</el-checkbox
                  >
                </p>

                <div v-if="!e.hidden" class="checkbox-menu">
                  <el-checkbox
                    v-for="i in e.children"
                    :label="i.id"
                    style="margin-top: 5px"
                    >{{ i.menuName }}</el-checkbox
                  >
                </div>
              </div>
            </el-checkbox-group>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-col>
    <el-col :span="8">
      <el-col :span="24" class="table-form-approve">
        <div>
          <p>权限组内账号</p>
          <el-select
            style="margin: 0 0 0 20px; width: 80%"
            v-model="value1"
            collapse-tags
            filterable
            multiple
            placeholder="请选择"
            @change="(e) => addItems(e)"
          >
            <el-option
              v-for="item in formOptions.forms[0].options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <h-table-list
            border
            type="local"
            :data="chooseRecords"
            :columns="columns"
            :form-options="formOptions"
            :show-pagination="false"
            @select="selectRows"
          >
            <template slot="operate-column" slot-scope="scope">
              <el-button @click="() => removeThis(scope.row)">移除</el-button>
            </template>
          </h-table-list>

          <!-- <TableAndButton
              list-loading="listLoading"
              :table-data="list"
              sort-change="sortChange"
              show-reviewer="false"
              :column-data="data.tableColumn"
              :operateButton="false"
            /> -->
        </div>
      </el-col>
    </el-col>
  </el-row>
</template>

<script>
import { mapState, mapMutations } from "vuex";
export default {
  props: ["dataId", "keyId", "getRightGroups", "removeFirst"], // dataId为数组匹配顺序 keyId为主键获取更新值
  inject: ["reload"],
  data() {
    return {
      value1: [],
      // checkList1: [],
      rules: {
        groupsName: [
          {
            required: "true",
            message: "请输入权限组名称",
          },
          {
            min: 2,
            max: 10,
            message: "请输入权限组名称,至少2个字",
            trigger: "blur",
          },
        ],
        groupsSort: [
          { required: "true", message: "请输入排序值", trigger: "blur" },
          {
            type: "number",
            min: 0,
            max: 999,
            message: "长度在 1 到 3位",
            trigger: "blur",
          },
        ],
      },
      formOptions: {
        showSearchBtn: false,
        showResetBtn: false,
        changevalue: (e) => {
          console.log(e);
          const data = [];
          e.userName.forEach((item) => {
            data.push(JSON.parse(item));
          });
          this.chooseRecords = data;
        },

        forms: [
          {
            prop: "userName",
            label: "添加用户",
            itemType: "select",
            itemWidth: "240",
            multiple: true,
            collapseTags: true,
            defaultValue: [],
            options: [{ value: "A", label: "A" }],
          },
        ],
      },
      columns: [
        { prop: "realName", label: "姓名", minWidth: "80" },
        { prop: "positionsName", label: "职位", minWidth: "80" },
        { prop: "operate", label: "操作", slotName: "operate-column" },
      ],
      menu1: true,
      editableTabsValue: "2",
      checkList: [],
      checkList1: [],
      editableTabs: [
        {
          title: "Tab 1",
          name: "1",
          content: "Tab 1 content",
        },
        {
          title: "Tab 2",
          name: "2",
          content: "Tab 2 content",
        },
      ],

      chooseRecords: [], // 当前权限组选择的用户
    };
  },
  mounted() {
    this.getRoleList();

    console.log("dataId", this.keyId);

    // 通过dataId关联数组,keyId请求菜单权限得checkList
    this.loadInfo();
  },
  computed: {
    ...mapState(["system_right", "app"]),
  },
  methods: {
    handleCheckAllChange(i, val) {
      console.log(this.$store.state.system_right.menuList);
      let items = [];
      // 这个地方找到合适的数值后跳出循环
      for (const item of this.$store.state.system_right.menuList) {
        if (item.children) {
          for (const e of item.children) {
            if (e.id == val) {
              items = e;
              break;
            }
          }
        }
      }
      // 得到选中数值的按钮组
      items = items.children.map((e) => {
        return e.menuId;
      });
      if (i) {
        // 选中

        this.checkList = [...this.checkList, ...items];

        this.checkList = Array.from(new Set(this.checkList));
      } else {
        // 反选
        // checkList.filter((x) => !items.some((e) => arr.indexOf(x) === e));
        // this.checkList.push(items)

        console.log(this.checkList);
        this.checkList = this.checkList.filter((e) => {
          return items.indexOf(e) == -1;
        });
      }
      console.log(this.checkList);
    },
    async getRoleList() {
      await this.$store.dispatch("system_right/requestRolesNoGroups");

      console.log(this.formOptions.forms[0], "+++this.formOptions.forms[0]+++");
    },
    loadInfo() {
      // 权限数据回填
      this.$store
        .dispatch("system_right/requestRightMenuList", this.keyId)
        .then((res) => {
          this.checkList = res
            ? res.data.map((e) => {
                return e.menuId;
              })
            : [];

          console.log("checkList", this.checkList);
        });
      // 权限组账号数据回填
      this.$store
        .dispatch("system_right/requestRightUserList", this.keyId)
        .then((res) => {
          console.log("userList", res);
          const array = res
            ? res.data.map((e) => {
                e.label = e.realName + `(${e.positionsName})`;
                e.value = e.userId; // JSON.stringify(e);
                return e;
              })
            : [];
          const combineData = this.$store.state.system_right.groupRoleList.concat(
            array
          );
          this.$set(this.formOptions.forms[0], "options", combineData);
          // 一个是表格回填，一个是选择框回填
          // this.forms[0].defaultValue=[1,2]//res.data
          const userName = res
            ? res.data.map((e) => {
                return e.userId;
              })
            : [];
          // TODO - defaultValue 设置不起作用
          this.formOptions.forms[0].defaultValue = userName;
          this.value1 = userName;
          this.chooseRecords = res ? res.data : [];
        });
    },
    addTab() {
      this.$confirm(
        `确认保存权限组？

权限变更内容将在用户下次登录后生效`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(async () => {
          this.$refs["ruleForm"].validate(async (valid) => {
            if (valid) {
              console.log(this.$store.state.system_right.menuList);
              const checkListIds = [...this.checkList];

              this.$store.state.system_right.menuList.map((item) => {
                if (item.children) {
                  item.children.map((e) => {
                    if (checkListIds.includes(e.id)) {
                      checkListIds.push(item.id);
                    } else {
                      checkListIds.forEach((i) => {
                        return i != item.id;
                      });
                    }
                  });
                }
              });
              const ids = this.chooseRecords.map((e) => {
                return e.userId;
              });

              const param = {
                groupsName: this.$store.state.system_right.groups[this.dataId]
                  .groupsName,
                groupsSort: this.$store.state.system_right.groups[this.dataId]
                  .groupsSort,
                resourceIds: checkListIds, // this.checkList,
                userIds: ids,
                id: this.keyId,
              };
              await this.$store.dispatch("system_right/saveGroups", param);
              this.getRightGroups();
            } else {
              console.log("error submit!!");
              return false;
            }
          });
        })
        .catch(() => {});
    },

    delTab() {
      this.$confirm(
        `确认删除权限组？

删除后组内所有账号都将清空操作权限`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(async () => {
        console.log(this.keyId, "keyid+++");
        console.log(this.editableTabs);

        if (!this.keyId) {
          this.removeFirst();
        } else {
          await this.$store.dispatch("system_right/delGroups", {
            id: this.keyId,
            groups: this.$store.state.system_right.groups,
          });
          this.getRightGroups();
        }
      });
    },
    addItems(e) {
      console.log(e);
      const items = this.$store.state.system_right.roleList.map((item) => {
        if (e.find((i) => i == item.value)) {
          return item;
        }
      });

      this.chooseRecords = items.filter((i) => i);
    },
    removeThis(row) {
      const userList = this.chooseRecords.filter((e) => {
        // if (e.userId != args.userId) {
        //     return e
        // }
        return e.userId != row.userId;
      });
      // TODO - 此处无法响应式修改多选框中的值

      this.value1 = userList.map((e) => e.value);
      this.chooseRecords = userList;
    },
  },
};
</script>
<style lang="scss">
.tablemenu-title {
  border-bottom: 2px solid #e4e4e4;
  padding: 12px 6px 12px 6px;
}
.checkbox-menu {
  height: 100px;
  padding: 5px;
  background: #eee;
}
</style>
